package com.qf.zsq.controller;

import com.qf.entity.CustomerEntity;
import com.qf.pojo.CustomerPojo;
import com.qf.util.StringUtil;
import com.qf.zsq.service.ICustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

@Controller
public class CustomerController {


    @Autowired
    ICustomerService customerService;

    @RequestMapping("login")
    public String login(String cname, String cpass, HttpServletRequest request){
        // 获取Subject对象;(当前用户对象)
        CustomerPojo cp=customerService.login(cname, StringUtil.MD5Encode(cpass));

        if(null==cp){
            request.setAttribute("msg","用户名或密码错误");
            return "login";
        }else{
            request.getSession().setAttribute("customer",cp);
            return "index";
        }

    }

    @RequestMapping("logout")
    public String logout( HttpSession session){
        session.removeAttribute("customer");
        return "index";
    }

    @RequestMapping("register")
    public String register(CustomerEntity ce, HttpServletRequest request, MultipartFile headImage) {
        //设置文件名
        String filename = com.qf.zsq.util.StringUtil.getUUID().substring(0, 5) + headImage.getOriginalFilename();
        //设置路径
        String realPath = request.getServletContext().getRealPath("images");
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdir();
        }
        //具体路径
        System.out.println(filename);
        String path = realPath + File.separator + filename;
        String path02 = "images/" + filename;
        ce.setCimage(path02);

        String password= StringUtil.MD5Encode(ce.getCpass());
        ce.setCpass(password);
        ce.setCaccount(ce.getCphone().substring(0,5)+StringUtil.getUUID().substring(0,5));
        boolean register = customerService.register(ce);
        try {
            InputStream is;
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            is = headImage.getInputStream();
            FileCopyUtils.copy(is, fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("msg", "注册成功!");
        return "login";
    }
}
